<?php
// $Id: video_upload.browser.inc,v 1.1.6.13 2010/09/28 18:51:33 bojanz Exp $

/**
 * @file video_upload.browser.inc
 * Provides functions for the Browser upload method.
 */

/**
 * Implementation of hook_widget().
 *
 * Copied from filefield.module
 */
function _video_upload_browser_method_widget(&$form, &$form_state, $field, $items, $delta = 0) {
  $item = array('list' => $field['list_default'], 'data' => array('description' => ''));
  if (isset($items[$delta])) {
    $item = array_merge($item, $items[$delta]);
  }

  $element = array(
    '#type' => 'video_upload_browser_method_widget',
    '#default_value' => $item,
    '#upload_validators' => array(),
  );

  return $element;
}

/**
 * Just like video_upload_widget_value, only without calling filefield
 * (no upload to save).
 */
function video_upload_browser_method_widget_value($element, $edit = FALSE) {
  if ($edit) {
    $item['video_id'] = isset($edit['video_id']) ? $edit['video_id'] : '';
    $item['video_status'] = isset($edit['video_status']) ? $edit['video_status'] : VIDEO_UPLOAD_STATUS_UNKNOWN;
    $item['video_status_ts'] = isset($edit['video_status_ts']) ? $edit['video_status_ts'] : $_SERVER['REQUEST_TIME'];
  }
  else {
    $item['video_id'] = '';
    $item['video_status'] = VIDEO_UPLOAD_STATUS_UNKNOWN;
    $item['video_status_ts'] = $_SERVER['REQUEST_TIME'];
  }

  $item['fid'] = NULL;
  $item['list'] = NULL;
  $item['data'] = NULL;

  return $item;
}

/**
 *  Build the element.
 */
function video_upload_browser_method_widget_process($element, $edit, &$form_state, $form) {
  if (empty($element['#value']['video_id']) && empty($element['#default_value']['video_id'])) {
    // No video ID yet, present the upload button.
    $element['video_notification'] = array(
      '#value' => '<noscript> <div class="video-upload-browser-noscript">' . t('You need to have JavaScript enabled in order to upload a video.') . '</div> </noscript>'
    );

    $element['video_browser_upload'] = array(
      '#type' => 'button',
      '#value' => t('Launch the Uploader'),
      '#attributes' => array('class' => 'video-upload-browser-upload',
                             'style' => 'display:none'),
    );
  }
  else {
    $value = (!empty($element['#value']['video_id'])) ? $element['#value'] : $element['#default_value'];

    // Video thumbnail, status, remove button.
    $element['video_item'] = array(
      '#type' => 'markup',
      '#value' => _video_upload_browser_method_form_item($value, $element['#id']),
    );
  }

  $element['video_status'] = array(
    '#type' => 'hidden',
    '#default_value' => $element['#default_value']['video_status'],
  );
  $element['video_status_ts'] = array(
    '#type' => 'hidden',
    '#default_value' => $element['#default_value']['video_status_ts'],
  );
  $element['video_id'] = array(
    '#type' => 'hidden',
    '#default_value' => $element['#default_value']['video_id'],
  );

  return $element;
}

/**
 * Here we render a video widget,
 */
function _video_upload_browser_method_form_item($item, $element_id) {
  $fake_field = array(
    'widget' => array(
      'display' => array(
        'thumb_width' => 120,
        'thumb_height' => 74,
      )
    )
  );

  $status_text = theme('video_upload_status_text', $item['video_status']);
  $thumb = theme('video_upload_video_thumb', $fake_field, $item, 0, FALSE);

  $markup = '<div id="' . $element_id . '-browser-item" class="video-upload-browser-item">';

  $markup .= '<div class="video-upload-browser-item-left">';
  $markup .= '<a href="http://www.youtube.com/v/' . $item['video_id'] . '">' . $thumb . '</a>';
  $markup .= '</div>';

  $markup .= '<div class="video-upload-browser-item-right">';
  $markup .= 'Status: ' . $status_text;
  $markup .= '<br /> <button class="form-submit video-upload-browser-delete" id="' . $element_id . '-video-browser-delete">Remove</button>';
  $markup .= '</div>';
  $markup .= '<div class="video-upload-clearer">&nbsp</div>';

  $markup .= '</div>';

  return $markup;
}

function theme_video_upload_browser_method_widget($element) {
  drupal_add_js('misc/jquery.form.js');
  drupal_add_js(drupal_get_path('module', 'video_upload') .'/video_upload_browser.js');
  drupal_add_css(drupal_get_path('module', 'video_upload') .'/video_upload_browser.css');

  jquery_ui_add(array('ui.dialog', 'ui.draggable', 'ui.resizable'));
  drupal_add_css(drupal_get_path('module', 'jquery_ui') ."/jquery.ui/themes/default/ui.all.css");

  // Add js settings to be used when requesting the pop-up form.
  if ($node = menu_get_object()) {
    $nid = $node->nid;
  }
  else {
    $nid = 0;
  }

  drupal_add_js(
    array('videoUpload-' . $element['#id'] => array(
      'fieldName' => $element['#field_name'],
      'typeName' => $element['#type_name']),
      'nid' => $nid,
    ),
    'setting'
  );

  return theme('video_upload_widget', $element);
}

function theme_video_upload_browser_method_widget_preview($item = NULL) {
  return theme('video_upload_widget_preview', $item);
}

/**
 * Callback. This is the page that youtube redirects to.
 * The reponse goes to an iframe and gets parsed.
 */
function video_upload_browser_method_success() {
  $value = array('video_id' => $_GET['id'],
                 'video_status' => 'unkown');

  $status = array('id' => $_GET['id'],
                  'success' => ($_GET['status'] == '200') ? TRUE : FALSE,
                  'field' => _video_upload_browser_method_form_item($value, '$element_id'),
                  );

  print drupal_to_js($status);
  exit;
}

function video_upload_browser_method_dialog($element_id, $field_name, $node_type, $nid) {
  $field = content_fields($field_name, $node_type);
  if ($nid) {
    $node = node_load($nid);
  }
  else {
    $node = new stdClass;
  }

  $messages = theme('status_messages');
  $form = drupal_get_form('video_upload_browser_method_upload_form', $element_id, $field, $node);

  echo $messages . $form;
  exit;
}

/**
 * Generate the pop-up form for uploading to YouTube.
 *
 * @param $form_state
 * @param $element_id
 * @param $field
 *   CCK field definition array.
 * @param $node
 *   The node object, or an empty stdClass when adding new nodes.
 */
function video_upload_browser_method_upload_form($form_state, $element_id, $field, $node) {
  video_upload_initialize_provider();

  // Authenticate to YouTube.
  // @TODO abstract out YouTube
  $http_client = _video_upload_authenticate_youtube();

  if (!$http_client) {
    // Unable to authenticate.
    return array();
  }

  $youtube = _video_upload_youtube($http_client);
  $video = _video_upload_video_entry();

  _video_upload_construct_media_group($youtube, $video, $node, $field);

  $token_array = _video_upload_get_token_array($youtube, $video);

  $form['#action'] = $token_array['url'] .= '?nexturl=' . url('video-upload/success', array('absolute' => TRUE));
  $form['#attributes']['enctype'] = 'multipart/form-data';

  $form['element_id'] = array(
    '#type' => 'hidden',
    '#value' => $element_id,
  );

  // YouTube upload token.
  // @TODO abstract out YouTube
  $form['token'] = array(
    '#type' => 'hidden',
    '#name' => 'token',
    '#value' => $token_array['token'],
  );

  $form['upload'] = array(
    '#type' => 'file',
    '#title' => t('Please select'),
    '#description' => filefield_validate_extensions_help($field['widget']['file_extensions']),
    '#size' => 35,
    '#attributes' => array(
      'accept' => implode(',', array_filter(explode(' ', $field['widget']['file_extensions']))),
    ),
  );

  return $form;
}